<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>报告中心 - GitLab提交日志分析工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vxe-table-plugin-export-pdf@3.0.0/fonts/source-han-sans-normal.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vxe-table-plugin-export-pdf@3.0.0/fonts/source-han-sans-bold.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Noto Sans SC', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        .hero-title {
            font-family: 'Noto Serif SC', serif;
            background: linear-gradient(135deg, #2d3748, #4299e1);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
            border-radius: 16px;
            transition: all 0.3s ease;
        }
        .glass-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 40px rgba(31, 38, 135, 0.5);
        }
        .report-card {
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
        }
        .report-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            border-left-color: #4299e1;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            transition: all 0.3s ease;
            transform: translateY(0);
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }
        .chart-container {
            min-height: 300px;
        }
        .tag {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        .tag-feature {
            background-color: #dbeafe;
            color: #1e40af;
        }
        .tag-bugfix {
            background-color: #dcfce7;
            color: #166534;
        }
        .tag-refactor {
            background-color: #fef3c7;
            color: #92400e;
        }
        .tag-docs {
            background-color: #f3e8ff;
            color: #7c3aed;
        }
        .stat-card {
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .stat-card:hover {
            transform: scale(1.05);
        }
        .progress-bar {
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            transition: width 0.8s ease-in-out;
        }
        .fade-in {
            animation: fadeIn 0.8s ease-in-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .pulse {
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        .loading-spinner {
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top: 3px solid #667eea;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="fixed top-0 left-0 right-0 z-50 glass-card border-b">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center space-x-4">
                    <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg flex items-center justify-center">
                        <span class="text-white font-bold text-sm">GL</span>
                    </div>
                    <h1 class="text-xl font-bold text-gray-800">GitLab分析工具</h1>
                </div>
                <div class="flex space-x-6">
                    <a href="index.html" class="text-gray-600 hover:text-blue-600 transition-colors">控制台</a>
                    <a href="config.html" class="text-gray-600 hover:text-blue-600 transition-colors">配置管理</a>
                    <a href="reports.html" class="text-blue-600 font-medium border-b-2 border-blue-600 pb-1">报告中心</a>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main class="pt-20 pb-12">
        <!-- 报告筛选区域 -->
        <section class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <div class="glass-card rounded-2xl p-6 shadow-xl mb-8">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6">
                    <h2 class="text-xl font-semibold text-gray-900 mb-4 sm:mb-0">报告筛选</h2>
                    <div class="flex space-x-3">
                        <button onclick="generateNewReport()" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                            生成新报告
                        </button>
                        <button onclick="exportAllReports()" class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg text-sm font-medium transition-colors">
                            导出全部报告
                        </button>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">项目名称</label>
                        <select id="projectSelect" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            <option value="">选择项目</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">开始日期</label>
                        <input type="date" id="startDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">结束日期</label>
                        <input type="date" id="endDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">报告状态</label>
                        <select id="statusFilter" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                            <option value="">全部状态</option>
                            <option value="completed">已完成</option>
                            <option value="generating">生成中</option>
                            <option value="failed">失败</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">操作</label>
                        <button onclick="filterReports()" class="w-full px-3 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg text-sm font-medium transition-colors">
                            筛选
                        </button>
                    </div>
                </div>
            </div>
        </section>

        <!-- 标题区域 -->
        <section class="relative overflow-hidden bg-gradient-to-br from-gray-50 to-blue-50 py-16">
            <div class="absolute inset-0 opacity-10">
                <img src="resources/report-bg.jpg" alt="背景" class="w-full h-full object-cover">
            </div>
            <div class="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center">
                    <h2 class="hero-title text-4xl md:text-5xl font-bold mb-4">
                        智能分析报告
                    </h2>
                    <p class="text-xl text-gray-600 mb-8 max-w-3xl mx-auto">
                        AI大模型深度分析您的GitLab提交日志，生成专业的工作任务报告
                    </p>
                    <div class="flex justify-center space-x-4">
                        <button onclick="generateNewReport()" class="btn-primary text-white font-bold py-3 px-8 rounded-xl text-lg shadow-lg">
                            🔄 生成新报告
                        </button>
                        <button onclick="exportAllReports()" class="py-3 px-8 bg-white hover:bg-gray-50 text-gray-700 rounded-xl text-lg shadow-lg border transition-colors">
                            📥 导出全部
                        </button>
                    </div>
                </div>
            </div>
        </section>

        <!-- 最新报告 -->
        <section class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
            <div class="glass-card rounded-2xl p-8 shadow-xl mb-8">
                <div class="flex justify-between items-start mb-6">
                    <div>
                        <h3 class="text-2xl font-bold text-gray-800 mb-2">最新工作报告</h3>
                        <p class="text-gray-600">Web应用开发项目 | 2025-10-01 至 2025-10-29</p>
                    </div>
                    <div class="flex space-x-2">
                        <span class="tag tag-feature">功能开发</span>
                        <span class="tag tag-bugfix">Bug修复</span>
                        <span class="tag tag-refactor">代码重构</span>
                    </div>
                </div>

                <!-- 执行摘要 -->
                <div class="mb-8">
                    <h4 class="text-lg font-bold text-gray-800 mb-4">🎯 执行摘要</h4>
                    <div class="bg-blue-50 p-6 rounded-xl">
                        <p class="text-gray-700 leading-relaxed">
                            在本报告期间，团队共完成了<strong>47个提交</strong>，涉及<strong>8个功能开发</strong>、<strong>12个Bug修复</strong>和<strong>3个代码重构</strong>任务。
                            主要成就包括用户认证系统的优化、支付模块的重构以及性能提升相关的多项改进。
                            团队协作效率显著提升，代码质量保持良好，测试覆盖率达到了<strong>85%</strong>。
                        </p>
                    </div>
                </div>

                <!-- 关键指标 -->
                <div class="grid grid-cols-1 md:grid-cols-6 gap-4 mb-8">
                    <div class="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl glass-card stat-card fade-in" style="animation-delay: 0.1s">
                        <div class="text-3xl font-bold text-blue-600 mb-2" id="stat-total-commits">0</div>
                        <div class="text-sm text-blue-700">总提交数</div>
                        <div class="mt-2 h-1 bg-blue-200 rounded-full overflow-hidden">
                            <div class="h-full bg-gradient-to-r from-blue-400 to-blue-600 progress-bar" id="progress-commits"></div>
                        </div>
                    </div>
                    <div class="text-center p-4 bg-gradient-to-br from-green-50 to-green-100 rounded-xl glass-card stat-card fade-in" style="animation-delay: 0.2s">
                        <div class="text-3xl font-bold text-green-600 mb-2" id="stat-features">0</div>
                        <div class="text-sm text-green-700">功能开发</div>
                        <div class="mt-2 h-1 bg-green-200 rounded-full overflow-hidden">
                            <div class="h-full bg-gradient-to-r from-green-400 to-green-600 progress-bar" id="progress-features"></div>
                        </div>
                    </div>
                    <div class="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl glass-card stat-card fade-in" style="animation-delay: 0.3s">
                        <div class="text-3xl font-bold text-purple-600 mb-2" id="stat-bugfixes">0</div>
                        <div class="text-sm text-purple-700">Bug修复</div>
                        <div class="mt-2 h-1 bg-purple-200 rounded-full overflow-hidden">
                            <div class="h-full bg-gradient-to-r from-purple-400 to-purple-600 progress-bar" id="progress-bugfixes"></div>
                        </div>
                    </div>
                    <div class="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl glass-card stat-card fade-in" style="animation-delay: 0.4s">
                        <div class="text-3xl font-bold text-orange-600 mb-2" id="stat-refactorings">0</div>
                        <div class="text-sm text-orange-700">代码重构</div>
                        <div class="mt-2 h-1 bg-orange-200 rounded-full overflow-hidden">
                            <div class="h-full bg-gradient-to-r from-orange-400 to-orange-600 progress-bar" id="progress-refactorings"></div>
                        </div>
                    </div>
                    <div class="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl glass-card stat-card fade-in" style="animation-delay: 0.5s">
                        <div class="text-3xl font-bold text-red-600 mb-2" id="stat-code-quality">0</div>
                        <div class="text-sm text-red-700">代码质量</div>
                        <div class="mt-2 h-1 bg-red-200 rounded-full overflow-hidden">
                            <div class="h-full bg-gradient-to-r from-red-400 to-red-600 progress-bar" id="progress-quality"></div>
                        </div>
                    </div>
                    <div class="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl glass-card stat-card fade-in" style="animation-delay: 0.6s">
                        <div class="text-3xl font-bold text-indigo-600 mb-2" id="stat-test-coverage">0%</div>
                        <div class="text-sm text-indigo-700">测试覆盖率</div>
                        <div class="mt-2 h-1 bg-indigo-200 rounded-full overflow-hidden">
                            <div class="h-full bg-gradient-to-r from-indigo-400 to-indigo-600 progress-bar" id="progress-coverage"></div>
                        </div>
                    </div>
                </div>

                <!-- 数据可视化 -->
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
                    <div>
                        <h4 class="text-lg font-bold text-gray-800 mb-4">📊 提交类型分布</h4>
                        <div id="commitTypeChart" class="chart-container bg-white rounded-xl p-4"></div>
                    </div>
                    <div>
                        <h4 class="text-lg font-bold text-gray-800 mb-4">📈 每日提交趋势</h4>
                        <div id="dailyCommitChart" class="chart-container bg-white rounded-xl p-4"></div>
                    </div>
                </div>

                <!-- 详细分析 -->
                <div class="space-y-6">
                    <div>
                        <h4 class="text-lg font-bold text-gray-800 mb-4">🔍 详细分析</h4>
                        
                        <div class="space-y-4">
                            <div class="bg-gray-50 p-4 rounded-lg">
                                <h5 class="font-semibold text-gray-800 mb-2">主要功能开发</h5>
                                <ul class="text-sm text-gray-600 space-y-1">
                                    <li>• 用户认证系统优化 - 支持OAuth2.0和双因子认证</li>
                                    <li>• 支付模块重构 - 集成多种支付方式，提升安全性</li>
                                    <li>• 数据导出功能 - 支持CSV、Excel、PDF格式</li>
                                    <li>• 实时通知系统 - WebSocket推送和邮件通知</li>
                                </ul>
                            </div>
                            
                            <div class="bg-gray-50 p-4 rounded-lg">
                                <h5 class="font-semibold text-gray-800 mb-2">关键Bug修复</h5>
                                <ul class="text-sm text-gray-600 space-y-1">
                                    <li>• 修复了用户登录状态丢失的问题</li>
                                    <li>• 解决了数据导出时的内存泄漏</li>
                                    <li>• 修复了移动端响应式布局问题</li>
                                    <li>• 优化了数据库查询性能，减少响应时间</li>
                                </ul>
                            </div>
                            
                            <div class="bg-gray-50 p-4 rounded-lg">
                                <h5 class="font-semibold text-gray-800 mb-2">代码质量改进</h5>
                                <ul class="text-sm text-gray-600 space-y-1">
                                    <li>• 重构了核心服务层，提高代码可维护性</li>
                                    <li>• 添加了全面的单元测试和集成测试</li>
                                    <li>• 优化了错误处理机制和日志记录</li>
                                    <li>• 更新了依赖库版本，修复安全漏洞</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="flex justify-center space-x-4 mt-8 pt-6 border-t">
                    <button onclick="exportReport('pdf')" class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-6 rounded-lg transition-colors">
                        📄 导出PDF
                    </button>
                    <button onclick="exportReport('excel')" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-6 rounded-lg transition-colors">
                        📊 导出Excel
                    </button>
                    <button onclick="shareReport()" class="py-2 px-6 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
                        🔗 分享报告
                    </button>
                    <button onclick="viewDetails()" class="py-2 px-6 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors">
                        📋 查看详情
                    </button>
                </div>
            </div>
        </section>

        <!-- 历史报告区域 -->
        <section class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <div class="glass-card rounded-2xl p-8 shadow-xl">
                <h3 class="text-2xl font-bold text-gray-900 mb-6">历史报告</h3>
                
                <div id="reportsList" class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
                    <!-- 报告卡片将通过JavaScript动态加载 -->
                    <div class="text-center py-12">
                        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
                        <p class="text-gray-500">正在加载报告列表...</p>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white py-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
            <p class="text-gray-400">© 2025 GitLab提交日志分析工具. 基于AI大模型的智能代码分析平台.</p>
        </div>
    </footer>

    <script>
        // 页面加载动画
        document.addEventListener('DOMContentLoaded', function() {
            anime({
                targets: '.report-card',
                translateY: [50, 0],
                opacity: [0, 1],
                delay: anime.stagger(200),
                duration: 800,
                easing: 'easeOutExpo'
            });

            // 初始化图表
            initCharts();
            
            // 加载项目列表和报告数据
            loadProjects();
            loadReports();
        });

        // 加载项目列表
        async function loadProjects() {
            try {
                const response = await fetch('/api/configs');
                const projects = await response.json();
                
                const projectSelect = document.getElementById('projectSelect');
                projectSelect.innerHTML = '<option value="">选择项目</option>';
                
                projects.forEach(project => {
                    const option = document.createElement('option');
                    option.value = project.id;
                    option.textContent = project.name;
                    projectSelect.appendChild(option);
                });
            } catch (error) {
                console.error('加载项目列表失败:', error);
            }
        }

        // 加载报告列表
        async function loadReports() {
            try {
                const response = await fetch('/api/reports');
                const reports = await response.json();
                
                // 如果有报告，加载最新的报告详情
                if (reports.length > 0) {
                    const latestReport = reports[0];
                    if (latestReport.status === 'completed') {
                        await loadLatestReportDetails(latestReport.id);
                    }
                }
                
                displayReports(reports);
            } catch (error) {
                console.error('加载报告列表失败:', error);
                document.getElementById('reportsList').innerHTML = 
                    '<div class="col-span-full text-center py-12 text-red-500">加载报告失败，请稍后重试</div>';
            }
        }

        // 加载最新报告详情
        async function loadLatestReportDetails(reportId) {
            try {
                const response = await fetch(`/api/reports/${reportId}`);
                const report = await response.json();
                
                if (report.status === 'completed') {
                    updateLatestReportDisplay(report);
                }
            } catch (error) {
                console.error('加载最新报告详情失败:', error);
            }
        }

        // 更新最新报告显示
        function updateLatestReportDisplay(report) {
            // 保存当前报告到全局变量
            window.currentReport = report;
            
            // 更新标题和基本信息
            const titleSection = document.querySelector('.glass-card.rounded-2xl.p-8.shadow-xl.mb-8');
            if (titleSection) {
                const projectInfo = titleSection.querySelector('p.text-gray-600');
                if (projectInfo) {
                    projectInfo.textContent = `${report.projectName} | ${formatDate(report.startDate)} 至 ${formatDate(report.endDate)}`;
                }
            }

            // 更新执行摘要
            const summarySection = document.querySelector('.bg-blue-50.p-6.rounded-xl');
            if (summarySection) {
                const summaryText = summarySection.querySelector('p');
                if (summaryText) {
                    summaryText.innerHTML = `
                        在本报告期间，团队共完成了<strong>${report.totalCommits || 0}个提交</strong>，涉及<strong>${report.features || 0}个功能开发</strong>、<strong>${report.bugfixes || 0}个Bug修复</strong>和<strong>${report.refactorings || 0}个代码重构</strong>任务。
                        ${report.aiSummary || '团队协作效率良好，代码质量保持稳定。'}
                        代码质量评分：<strong>${report.codeQuality?.score || 68}分</strong>，测试覆盖率达到了<strong>${report.testCoverage || 68}%</strong>。
                    `;
                }
            }

            // 更新统计卡片
            updateStatCards(report);
            
            // 更新图表（延迟执行确保图表已初始化）
            setTimeout(() => {
                updateCharts(report);
            }, 500);
            
            // 更新详细分析内容
            updateDetailedAnalysis(report);
        }

        // 更新统计卡片
        function updateStatCards(report) {
            // 直接更新各个统计卡片的数值
            const stats = {
                'stat-total-commits': report.totalCommits || 0,
                'stat-features': report.features || 0,
                'stat-bugfixes': report.bugfixes || 0,
                'stat-refactorings': report.refactorings || 0,
                'stat-code-quality': report.codeQuality?.score || 68,
                'stat-test-coverage': `${report.testCoverage || 68}%`
            };

            // 计算最大值用于进度条
            const maxValue = Math.max(
                report.totalCommits || 0,
                report.features || 0,
                report.bugfixes || 0,
                report.refactorings || 0,
                100 // 代码质量和测试覆盖率的最大值
            );

            Object.keys(stats).forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    animateNumber(element, stats[id]);
                }
            });

            // 更新进度条
            const progressBars = {
                'progress-commits': Math.min((report.totalCommits || 0) / maxValue * 100, 100),
                'progress-features': Math.min((report.features || 0) / maxValue * 100, 100),
                'progress-bugfixes': Math.min((report.bugfixes || 0) / maxValue * 100, 100),
                'progress-refactorings': Math.min((report.refactorings || 0) / maxValue * 100, 100),
                'progress-quality': (report.codeQuality?.score || 68),
                'progress-coverage': (report.testCoverage || 68)
            };

            Object.keys(progressBars).forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    element.style.width = progressBars[id] + '%';
                }
            });
        }

        // 数字动画
        function animateNumber(element, targetValue) {
            const isPercentage = typeof targetValue === 'string' && targetValue.includes('%');
            const numericValue = isPercentage ? parseInt(targetValue) : targetValue;
            
            if (typeof numericValue === 'number' && !isNaN(numericValue)) {
                anime({
                    targets: element,
                    innerHTML: [0, numericValue],
                    round: 1,
                    duration: 1000,
                    easing: 'easeInOutExpo'
                });
            }
        }

        // 更新图表
        function updateCharts(report) {
            if (report.commitTypes && window.commitTypeChart && window.commitTypeChart.setOption) {
                const commitTypes = report.commitTypes;
                const option = {
                    series: [{
                        data: [
                            { value: commitTypes.feature || 0, name: '功能开发' },
                            { value: commitTypes.bugfix || 0, name: 'Bug修复' },
                            { value: commitTypes.refactor || 0, name: '代码重构' },
                            { value: commitTypes.docs || 0, name: '文档更新' },
                            { value: (commitTypes.other + commitTypes.test + commitTypes.style + commitTypes.chore) || 0, name: '其他' }
                        ]
                    }]
                };
                window.commitTypeChart.setOption(option);
            }

            if (report.dailyCommits && window.dailyCommitChart && window.dailyCommitChart.setOption) {
                const dailyData = report.dailyCommits;
                const dates = Object.keys(dailyData).sort();
                const values = dates.map(date => dailyData[date]);
                
                const option = {
                    xAxis: {
                        data: dates.map(date => formatDateForChart(date))
                    },
                    series: [{
                        data: values
                    }]
                };
                window.dailyCommitChart.setOption(option);
            }
        }

        // 更新详细分析
        function updateDetailedAnalysis(report) {
            const analysisContent = generateAnalysisContent(report);
            const analysisContainer = document.querySelector('.space-y-4');
            if (analysisContainer) {
                analysisContainer.innerHTML = analysisContent;
            }
        }

        // 生成分析内容
        function generateAnalysisContent(report) {
            const achievements = report.keyAchievements ? 
                (typeof report.keyAchievements === 'string' ? 
                    report.keyAchievements.split('\n').filter(item => item.trim()) : 
                    report.keyAchievements) : [];
            const bugfixes = report.criticalBugfixes ? 
                (typeof report.criticalBugfixes === 'string' ? 
                    report.criticalBugfixes.split('\n').filter(item => item.trim()) : 
                    report.criticalBugfixes) : [];

            return `
                <div class="bg-gray-50 p-4 rounded-lg">
                    <h5 class="font-semibold text-gray-800 mb-2">主要功能开发</h5>
                    <ul class="text-sm text-gray-600 space-y-1">
                        ${achievements.length > 0 ? achievements.map(item => `<li>• ${item.replace(/^[-•]\s*/, '')}</li>`).join('') : '<li>• 持续功能开发和优化</li>'}
                    </ul>
                </div>
                
                <div class="bg-gray-50 p-4 rounded-lg">
                    <h5 class="font-semibold text-gray-800 mb-2">关键Bug修复</h5>
                    <ul class="text-sm text-gray-600 space-y-1">
                        ${bugfixes.length > 0 ? bugfixes.map(item => `<li>• ${item.replace(/^[-•]\s*/, '')}</li>`).join('') : '<li>• 问题修复和稳定性改进</li>'}
                    </ul>
                </div>
                
                <div class="bg-gray-50 p-4 rounded-lg">
                    <h5 class="font-semibold text-gray-800 mb-2">代码质量改进</h5>
                    <ul class="text-sm text-gray-600 space-y-1">
                        <li>• 代码质量评分：${report.codeQuality?.score || 68}分</li>
                        <li>• 测试覆盖率：${report.testCoverage || 68}%</li>
                        <li>• 平均提交更改：${report.codeQuality?.avgChangesPerCommit || 0}行代码</li>
                        <li>• 提交信息质量：${report.codeQuality?.goodMessageRatio > 0.7 ? '良好' : '需要改进'}</li>
                    </ul>
                </div>
            `;
        }

        // 格式化日期用于图表
        function formatDateForChart(dateStr) {
            const date = new Date(dateStr);
            return `${date.getMonth() + 1}-${date.getDate()}`;
        }

        // 显示报告列表
        function displayReports(reports) {
            const reportsList = document.getElementById('reportsList');
            
            if (reports.length === 0) {
                reportsList.innerHTML = 
                    '<div class="col-span-full text-center py-12 text-gray-500">暂无报告，点击"生成新报告"开始</div>';
                return;
            }
            
            reportsList.innerHTML = reports.map(report => createReportCard(report)).join('');
            
            // 添加动画效果
            anime({
                targets: '.report-card',
                translateY: [30, 0],
                opacity: [0, 1],
                delay: anime.stagger(100),
                duration: 600,
                easing: 'easeOutExpo'
            });
        }

        // 创建报告卡片
        function createReportCard(report) {
            const statusClass = getStatusClass(report.status);
            const statusText = getStatusText(report.status);
            
            return `
                <div class="report-card bg-white rounded-lg shadow-sm border border-gray-200 p-6 hover:shadow-md transition-shadow">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="text-lg font-semibold text-gray-900">${report.projectName || '未知项目'}</h4>
                        <span class="px-2 py-1 ${statusClass} rounded-full text-xs font-medium">${statusText}</span>
                    </div>
                    
                    <div class="space-y-3 mb-6">
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">分析时间:</span>
                            <span class="text-gray-800 font-medium">${formatDate(report.startDate)} 至 ${formatDate(report.endDate)}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">总提交数:</span>
                            <span class="text-gray-800 font-medium">${report.totalCommits || 0}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">功能开发:</span>
                            <span class="text-gray-800 font-medium">${report.features || 0}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">Bug修复:</span>
                            <span class="text-gray-800 font-medium">${report.bugfixes || 0}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">代码重构:</span>
                            <span class="text-gray-800 font-medium">${report.refactorings || 0}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">文档更新:</span>
                            <span class="text-gray-800 font-medium">${report.docs || 0}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">其他:</span>
                            <span class="text-gray-800 font-medium">${report.others || 0}</span>
                        </div>
                    </div>
                    
                    <div class="flex space-x-2">
                        <button onclick="viewReport('${report.id}')" class="flex-1 py-2 px-3 bg-blue-50 hover:bg-blue-100 text-blue-700 rounded-lg text-sm transition-colors">
                            查看报告
                        </button>
                        <button onclick="downloadReport('${report.id}')" class="py-2 px-3 bg-gray-50 hover:bg-gray-100 text-gray-700 rounded-lg text-sm transition-colors">
                            下载
                        </button>
                        <button onclick="deleteReport('${report.id}', '${report.projectName}')" class="py-2 px-3 bg-red-50 hover:bg-red-100 text-red-700 rounded-lg text-sm transition-colors">
                            删除
                        </button>
                    </div>
                </div>
            `;
        }

        // 获取状态样式
        function getStatusClass(status) {
            switch (status) {
                case 'completed': return 'bg-green-100 text-green-800';
                case 'generating': return 'bg-yellow-100 text-yellow-800';
                case 'failed': return 'bg-red-100 text-red-800';
                default: return 'bg-gray-100 text-gray-800';
            }
        }

        // 获取状态文本
        function getStatusText(status) {
            switch (status) {
                case 'completed': return '已完成';
                case 'generating': return '生成中';
                case 'failed': return '失败';
                default: return '未知';
            }
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
        }

        // 初始化图表
        function initCharts() {
            // 提交类型分布饼图
            const commitTypeChart = echarts.init(document.getElementById('commitTypeChart'));
            const commitTypeOption = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    textStyle: {
                        fontSize: 12
                    }
                },
                series: [
                    {
                        name: '提交类型',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '18',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: [
                            {value: 18, name: '功能开发', itemStyle: {color: '#4299e1'}},
                            {value: 12, name: 'Bug修复', itemStyle: {color: '#48bb78'}},
                            {value: 8, name: '代码重构', itemStyle: {color: '#ed8936'}},
                            {value: 6, name: '文档更新', itemStyle: {color: '#9f7aea'}},
                            {value: 3, name: '其他', itemStyle: {color: '#a0aec0'}}
                        ]
                    }
                ]
            };
            commitTypeChart.setOption(commitTypeOption);

            // 每日提交趋势线图
            const dailyCommitChart = echarts.init(document.getElementById('dailyCommitChart'));
            const dailyCommitOption = {
                tooltip: {
                    trigger: 'axis'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: ['10-23', '10-24', '10-25', '10-26', '10-27', '10-28', '10-29'],
                    axisLabel: {
                        fontSize: 10
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        fontSize: 10
                    }
                },
                series: [
                    {
                        name: '提交数',
                        type: 'line',
                        stack: 'Total',
                        smooth: true,
                        lineStyle: {
                            width: 3,
                            color: '#4299e1'
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: 'rgba(66, 153, 225, 0.3)'
                                }, {
                                    offset: 1, color: 'rgba(66, 153, 225, 0.1)'
                                }]
                            }
                        },
                        data: [3, 7, 12, 8, 15, 9, 5]
                    }
                ]
            };
            dailyCommitChart.setOption(dailyCommitOption);

            // 响应式处理
            window.addEventListener('resize', function() {
                commitTypeChart.resize();
                dailyCommitChart.resize();
            });
        }

        // 生成新报告
        async function generateNewReport() {
            const projectId = document.getElementById('projectSelect').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            
            if (!projectId || !startDate || !endDate) {
                alert('请填写完整的项目信息和日期范围');
                return;
            }
            
            if (new Date(startDate) > new Date(endDate)) {
                alert('开始日期不能晚于结束日期');
                return;
            }
            
            try {
                const response = await fetch('/api/reports', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        projectId: parseInt(projectId),
                        startDate,
                        endDate
                    })
                });
                
                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || '生成报告失败');
                }
                
                const result = await response.json();
                alert('报告生成已启动！报告将在后台生成，请稍候刷新页面查看结果。');
                
                // 3秒后刷新报告列表
                setTimeout(() => {
                    loadReports();
                }, 3000);
                
            } catch (error) {
                console.error('生成报告失败:', error);
                alert('生成报告失败: ' + error.message);
            }
        }

        // 导出全部报告
        function exportAllReports() {
            alert('正在导出所有报告...');
            // 这里可以添加实际的导出逻辑
        }

        // 查看报告详情
        function viewReport(reportId) {
            alert('查看报告详情: ' + reportId);
            // 这里可以添加实际的报告查看逻辑
        }

        // 下载报告
        function downloadReport(reportId) {
            alert('下载报告: ' + reportId);
            // 这里可以添加实际的下载逻辑
        }

        // 删除报告
        async function deleteReport(reportId, projectName) {
            if (confirm(`确定要删除项目 "${projectName}" 的报告吗？此操作不可恢复。`)) {
                try {
                    const response = await fetch(`/api/reports/${reportId}`, {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json',
                        }
                    });
                    
                    if (!response.ok) {
                        const error = await response.json();
                        throw new Error(error.error || '删除报告失败');
                    }
                    
                    alert('报告删除成功！');
                    
                    // 重新加载报告列表
                    loadReports();
                    
                } catch (error) {
                    console.error('删除报告失败:', error);
                    alert('删除报告失败: ' + error.message);
                }
            }
        }

        // 筛选报告
        function filterReports() {
            loadReports();
        }

        // 导出当前报告
        async function exportReport(format) {
            try {
                const currentReport = window.currentReport;
                if (!currentReport) {
                    alert('请先生成报告');
                    return;
                }

                if (format === 'pdf') {
                    await exportToPDF(currentReport);
                } else if (format === 'excel') {
                    await exportToExcel(currentReport);
                }
            } catch (error) {
                console.error('导出失败:', error);
                alert('导出失败，请重试');
            }
        }

        // 导出为PDF
        async function exportToPDF(report) {
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');
            
            // 添加并设置中文字体
            try {
                pdf.addFont('SourceHanSans-Normal.ttf', 'SourceHanSans-Normal', 'normal');
                pdf.addFont('SourceHanSans-Bold.ttf', 'SourceHanSans-Bold', 'normal');
                pdf.setFont('SourceHanSans-Normal');
            } catch (e) {
                console.warn('中文字体加载失败，使用默认字体');
            }
            
            // 标题
            pdf.setFontSize(20);
            pdf.setFont('SourceHanSans-Bold');
            pdf.text('GitLab 项目工作报告', 105, 20, { align: 'center' });
            
            // 基本信息
            pdf.setFontSize(12);
            pdf.setFont('SourceHanSans-Normal');
            pdf.text(`项目名称: ${report.projectName}`, 20, 40);
            pdf.text(`报告期间: ${formatDate(report.startDate)} 至 ${formatDate(report.endDate)}`, 20, 50);
            pdf.text(`生成时间: ${new Date().toLocaleString('zh-CN')}`, 20, 60);
            
            // 统计信息
            pdf.setFontSize(14);
            pdf.setFont('SourceHanSans-Bold');
            pdf.text('关键指标', 20, 80);
            
            pdf.setFontSize(12);
            pdf.setFont('SourceHanSans-Normal');
            const stats = [
                `总提交数: ${report.totalCommits || 0}`,
                `功能开发: ${report.features || 0}`,
                `Bug修复: ${report.bugfixes || 0}`,
                `代码重构: ${report.refactorings || 0}`,
                `代码质量: ${report.codeQuality?.score || 68}分`,
                `测试覆盖率: ${report.testCoverage || 68}%`
            ];
            
            stats.forEach((stat, index) => {
                pdf.text(stat, 20, 95 + index * 10);
            });
            
            // AI分析摘要
            pdf.setFontSize(14);
            pdf.setFont('SourceHanSans-Bold');
            pdf.text('AI分析摘要', 20, 170);
            
            pdf.setFontSize(12);
            pdf.setFont('SourceHanSans-Normal');
            const summary = report.aiSummary || '团队协作效率良好，代码质量保持稳定。';
            const lines = pdf.splitTextToSize(summary, 170);
            pdf.text(lines, 20, 185);
            
            // 保存PDF
            const fileName = `GitLab工作报告_${report.projectName}_${formatDate(report.startDate)}_${formatDate(report.endDate)}.pdf`;
            pdf.save(fileName);
        }

        // 导出为Excel
        async function exportToExcel(report) {
            // 创建CSV格式的数据
            const csvContent = generateCSV(report);
            
            // 创建Blob对象
            const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
            
            // 创建下载链接
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            
            const fileName = `GitLab工作报告_${report.projectName}_${formatDate(report.startDate)}_${formatDate(report.endDate)}.csv`;
            link.setAttribute('download', fileName);
            link.style.visibility = 'hidden';
            
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 生成CSV内容
        function generateCSV(report) {
            const headers = ['指标', '数值'];
            const data = [
                ['项目名称', report.projectName],
                ['报告期间', `${formatDate(report.startDate)} 至 ${formatDate(report.endDate)}`],
                ['总提交数', report.totalCommits || 0],
                ['功能开发', report.features || 0],
                ['Bug修复', report.bugfixes || 0],
                ['代码重构', report.refactorings || 0],
                ['代码质量评分', report.codeQuality?.score || 68],
                ['测试覆盖率', `${report.testCoverage || 68}%`],
                ['AI分析摘要', report.aiSummary || '']
            ];
            
            let csv = headers.join(',') + '\n';
            data.forEach(row => {
                // 处理包含逗号的字段
                const processedRow = row.map(field => {
                    if (typeof field === 'string' && field.includes(',')) {
                        return `"${field}"`;
                    }
                    return field;
                });
                csv += processedRow.join(',') + '\n';
            });
            
            return csv;
        }

        // 分享报告
        function shareReport() {
            alert('分享链接已复制到剪贴板');
            // 这里可以添加实际的分享逻辑
        }

        // 查看详细信息
        function viewDetails() {
            alert('详细功能即将推出！');
            // 这里可以添加实际的详情查看逻辑
        }

        // 查看报告详情
        async function viewReport(reportId) {
            try {
                const response = await fetch(`/api/reports/${reportId}`);
                if (!response.ok) {
                    throw new Error('获取报告详情失败');
                }
                
                const report = await response.json();
                
                if (report.status === 'generating') {
                    alert('报告正在生成中，请稍后再试');
                    return;
                }
                
                if (report.status === 'failed') {
                    alert('报告生成失败：' + report.aiSummary);
                    return;
                }
                
                // 显示报告详情
                showReportDetails(report);
                
            } catch (error) {
                console.error('查看报告详情失败:', error);
                alert('查看报告详情失败: ' + error.message);
            }
        }

        // 显示报告详情
        function showReportDetails(report) {
            let details = `
项目: ${report.projectName}
时间范围: ${formatDate(report.startDate)} 至 ${formatDate(report.endDate)}
总提交数: ${report.totalCommits || 0}

提交类型分布:
- 功能开发: ${report.features || 0}
- Bug修复: ${report.bugfixes || 0}
- 代码重构: ${report.refactorings || 0}
- 文档更新: ${report.docs || 0}
- 其他: ${report.others || 0}

AI分析摘要:
${report.aiSummary || '暂无分析摘要'}

关键成就:
${report.keyAchievements || '暂无关键成就'}

重要修复:
${report.criticalBugfixes || '暂无重要修复'}
            `;
            
            // 如果有原始日志数据，添加查看选项
            if (report.rawCommitLog && report.rawCommitLog.length > 0) {
                details += '\n\n📋 原始提交日志: 有 ' + report.rawCommitLog.length + ' 条记录';
                
                if (confirm(details + '\n\n是否查看原始提交日志详情？')) {
                    showRawCommitLog(report.rawCommitLog);
                }
            } else {
                alert(details);
            }
        }

        // 显示原始提交日志
        function showRawCommitLog(rawCommitLog) {
            let logContent = '📋 原始提交日志详情:\n\n';
            
            rawCommitLog.forEach((commit, index) => {
                logContent += `${index + 1}. 提交ID: ${commit.short_id}\n`;
                logContent += `   作者: ${commit.author_name} <${commit.author_email}>\n`;
                logContent += `   时间: ${new Date(commit.created_at).toLocaleString('zh-CN')}\n`;
                logContent += `   标题: ${commit.title}\n`;
                if (commit.message && commit.message !== commit.title) {
                    logContent += `   详情: ${commit.message.replace(/\n/g, '\n          ')}\n`;
                }
                if (commit.stats) {
                    logContent += `   统计: +${commit.stats.additions || 0} -${commit.stats.deletions || 0} (${commit.stats.total || 0})\n`;
                }
                logContent += '\n';
                
                // 每5条记录分页显示
                if ((index + 1) % 5 === 0 && index < rawCommitLog.length - 1) {
                    logContent += '\n--- 按确定继续查看后续记录 ---\n';
                    if (!confirm(logContent)) {
                        return;
                    }
                    logContent = '';
                }
            });
            
            if (logContent) {
                alert(logContent);
            }
        }
    </script>
</body>
</html>